import SimpleHTTPServer
import SocketServer
import cookielib
import os
from threading import Thread
import urllib
import urllib2

#current running proxy and its port number
PROXY = None
PROXY_PORT = 8000

#real server address and login data
SERVER = "http://client.webeffector.ru"
LOGIN_DATA = ( SERVER + '/j_spring_security_check', {'j_username': 'user', 'j_password': 'ghtdtl.pth'}, 'POST', None)

#opened cookie session
SERVER_SESSION = None

# a root directory, containing script and profiles directory
ROOT_DIR = os.getcwd()

# a name of a directory where all profiles resides
PROFILES = 'profiles'


#set data for url
def seturl( url, data ):
    dir = url[1:]
    createFile( dir, data )

#checks if given url exists
def checkurl( url ):
    exists = True
    try:
        open( url[1:] )
    except :
        exists = False
    return exists

#creates dir if it doesnt exists yet
def createDir( path ):
    try:
        os.makedirs( path )
    except:
        pass

#creates file if it doesnt exists yet
#setting its content to content
def createFile( path, content ):
    try:
        if '/' in path:
            dir = path[:path.rindex('/')]
            createDir( dir )
        f = open( path, 'w' )
        f.write( content )
        f.close()
    except Exception as e:
        print e


#urldef format is (url,params,method,session,)
def loadurl( urldef ):
    opener = urldef[3]
    if opener is None:
        cj = cookielib.MozillaCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    # encoding params
    enc = urllib.urlencode( urldef[1] )

    # GET or POST data to url
    if urldef[2] == 'POST':
        r = opener.open( urldef[0], enc )
    else:
        if len( urldef[1]) > 0:
            enc = "?%s" % enc
        r = opener.open( urldef[0] + enc )
    return r, opener

#create a proxy for given url
def urlproxy( url, urldef ):
    r,o = loadurl( urldef )
    seturl( url, r.fp.read())

#simple http server proxy
class CachingHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def do_GET(self):
        self.prehandle()
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

    def do_HEAD(self):
        self.prehandle()
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)

    def prehandle(self):
        global SERVER_SESSION
        global SERVER
        #getting url without params
        url = self.path
        if '?' in url:
            url = url[:url.rindex('?')]
        
        #check if already cached
        if checkurl( url ) is False:
            urlproxy( url, (SERVER + self.path, {}, 'GET', SERVER_SESSION))
            print "CREATED PROXY local:%s for %s%s" % (url,SERVER,self.path)


class CachingServer(Thread):
    #http server instance
    serv = None

    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global SERVER_SESSION
        print "Trying to login to %s..." % SERVER
        SERVER_SESSION = loadurl( LOGIN_DATA )[1]
        print "Starting stub..."
        Handler = CachingHandler
        self.serv = SocketServer.TCPServer(("", PROXY_PORT), Handler)
        print "serving at port %d" % PROXY_PORT
        self.serv.serve_forever()

    def stop(self):
        print "Stopping server..."
        self.serv.shutdown()

#start server
def start( cnf='Default' ):
    global PROXY
    cnfdir = "%s/%s" % (PROFILES,cnf,)
    createDir( cnfdir )
    os.chdir( cnfdir )
    PROXY = CachingServer()
    PROXY.start()

#stop server
def stop():
    os.chdir( ROOT_DIR )
    if PROXY is not None:
        PROXY.stop()


# TODO:
# 1. multiple configurations (done)
# 2. run server in separate thread (done)
# 3. handle images properly
# 4. url operations: reset,content,handlers in python
# 5. no-cache list (files, masks etc)

if __name__ == '__main__':
    f = open('user/images/ahtung.png')
    